<template>
    <van-nav-bar title="购物车" />
    <van-card v-for="item in carlst" :key="item.id" :num="item.num" :price="item.price" :desc="item.desc"
        :title="item.name" :thumb="item.img">
        <template #tags>
            <!-- <van-tag plain type="primary">标签</van-tag> -->
            <van-stepper v-model="item.count" @change="calculatetheprice" input-width="30px" button-size="20px" />
        </template>
        <template #footer>
            <van-checkbox-group v-model="checkedResult" @change="checkedResultChange">
                <van-checkbox :name="item.id" @click="calculatetheprice" />
            </van-checkbox-group>
            <van-button size="mini">看详情</van-button>
        </template>
    </van-card>
    <van-submit-bar :price="price" button-text="提交订单" @submit="onSubmit" style="margin-bottom:50px;">
        <van-checkbox v-model="isCheckAll" @change="checkAllChange">全选</van-checkbox>
        <!-- <template #tip>
            你的收货地址不支持配送, <span @click="onClickLink">修改地址</span>
        </template> -->
    </van-submit-bar>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref, onMounted } from 'vue'
import http from '../../http';

// 复选框
const list = ref([]);
const isCheckAll = ref(false);
const checkedResult = ref();
const price = ref(0);
const countlist = ref([])
const checkAllChange = (val) => {
    checkedResult.value = val ? list.value : []
}
const calculatetheprice = () => {
    const checkedData = checkedResult.value
    if (!checkedData) {
        return
    }
    price.value = 0
    for (let i = 0; i < carlst.value.length; i++) {
        if (checkedData.includes(carlst.value[i].id)) {
            price.value += carlst.value[i].price * carlst.value[i].count * 100
        }
    }
}
const checkedResultChange = (value) => {
    const checkedCount = value.length
    isCheckAll.value = checkedCount === list.value.length
    calculatetheprice()
}

// 数据
const router = useRouter()
const tmoney = ref(0)
const carlst = ref([])
const onSubmit = () => {
    if (!checkedResult.value) {
        return
    }
    for (let i = 0; i < carlst.value.length; i++) {
        if (checkedResult.value.includes(carlst.value[i].id)) {
            countlist.value.push(carlst.value[i].count)
        }
    }
    router.push({
        path: '/order',
        query: {
            price: JSON.stringify(price.value),
            goods: JSON.stringify(checkedResult.value),
            countlist: JSON.stringify(countlist.value)
        }
    })
}
const getCarData = () => {
    http.get('shop/cart/', {
        params: {
            userid: localStorage.getItem('userid')
        }
    }).then(res => {
        carlst.value = res.data.clist
        tmoney.value = res.data.tmoney * 100
        const car = res.data.clist
        for (let i = 0; i < car.length; i++) {
            list.value.push(car[i].id)
        }
    })
}
onMounted(() => {
    getCarData()
})
</script>

<style scoped></style>